<template>
  <div>
    <el-table
        :data="tableData"
        style="width: 100%">
      <el-table-column
          prop="cropsId"
          label="货物编号">
      </el-table-column>
      <el-table-column
          prop="farmerNickName"
          label="通知人">
      </el-table-column>
      <el-table-column
          prop="farmerDept"
          label="部门">
      </el-table-column>
      <el-table-column
          prop="time"
          label="时间">
      </el-table-column>
      <el-table-column
          prop="remarks"
          label="备注">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status==0">未运输</el-tag>
          <el-tag v-if="scope.row.status==1">运输中</el-tag>
          <el-tag v-if="scope.row.status==2">已运输</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="startTransport(scope.row)" v-if="scope.row.status==0">开始配送
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="transportLocation(scope.row)" v-if="scope.row.status==1">中途定位
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="transportOk(scope.row)" v-if="scope.row.status==1">配送完毕
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div id="container"></div>
  </div>
</template>

<script>
import {formatDate} from "@/utils"
import VueAMap from 'vue-amap'
import AMapLoader from '@amap/amap-jsapi-loader'
import Api from "@/utils/api";
export default {
  name: "DriverView",
  data() {
    return {
      tableData: [],
      cityDetail: '',
      lng: Number,
      lat: Number
    }
  },
  created() {
    this.load();
    // this.initAMap()
  },
  methods: {
    load() {
      this.axios.post("/driver/driver/list?driverId=chenliang").then(res => {
        this.tableData = res.data.data;
      })
    },
    /**
     * 开始配送
     * @param row
     */
    startTransport(row) {
      const transportArray = [];
      const id = new this.$snowFlakeId().generate();
      transportArray.push(id);
      transportArray.push(id);
      transportArray.push("chenliang");
      transportArray.push("陈亮");
      transportArray.push("10086");
      transportArray.push("百色运输部");
      transportArray.push(formatDate(new Date()));
      transportArray.push(this.cityDetail);
      transportArray.push(row.cropsId);
      transportArray.push('始发地');
      this.$confirm('是否开始运送货物', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            this.$httpBlock
                .post(this.$httpUrl + '/driverapi/createTransport', {transportArray: transportArray})
                .then(res => {
                  if (res.status === 200) {
                    this.$message.success('数据上链成功');
                    const transportInfo = {
                      lng: Number(this.lng),
                      lat: Number(this.lat),
                      cropsId: row.cropsId,
                      id: row.id,
                      status: 1,
                    }
                    this.axios.post("/driver/driver/saveTransport", transportInfo).then(res => {
                      if (res.data.data) {
                        this.load()
                      }
                    })
                  }
                })
                .catch(err => {
                  this.$message.error('存储异常 ' + err);
                });
            this.$message({
              type: 'success',
              message: '开始运送!'
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消运送'
            });
          });
    },
    /**
     * 配送完成
     * @param row
     */
    transportOk(row) {
      const transportArray = [];
      const id = new this.$snowFlakeId().generate();
      transportArray.push(id);
      transportArray.push(id);
      transportArray.push("chenliang");
      transportArray.push("陈亮");
      transportArray.push("10086");
      transportArray.push("百色运输部");
      transportArray.push(formatDate(new Date()));
      transportArray.push(this.cityDetail);
      transportArray.push(row.cropsId);
      transportArray.push('终点站');
      this.$confirm('是否确认配送完毕', '配送', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            this.$httpBlock
                .post(this.$httpUrl + '/driverapi/createTransport', {transportArray: transportArray})
                .then(res => {
                  if (res.status === 200) {
                    this.$message.success('数据上链成功');
                    const transportInfo = {
                      lng: Number(this.lng),
                      lat: Number(this.lat),
                      cropsId: row.cropsId,
                      status: 2,
                      id: row.id,
                      outFactoryStatus: 0
                    };
                    this.axios.post("/driver/driver/saveTransport", transportInfo).then(res => {
                      if (res.data.data) {
                        this.load()
                      }
                    })
                  }
                })
                .catch(err => {
                  this.$message.error('存储异常 ' + err);
                });
            this.$message({
              type: 'success',
              message: '配送成功!'
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消'
            });
          });
    },
    transportLocation(row) {
      const transportArray = [];
      const id = new this.$snowFlakeId().generate();
      transportArray.push(id);
      transportArray.push(id);
      transportArray.push("chenliang");
      transportArray.push("陈亮");
      transportArray.push("10086");
      transportArray.push("百色运输部");
      transportArray.push(formatDate(new Date()));
      transportArray.push(this.cityDetail);
      transportArray.push(row.cropsId);
      transportArray.push('中途定位');
      this.$confirm(this.cityDetail, '定位', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            this.$httpBlock
                .post(this.$httpUrl + '/driverapi/createTransport', {transportArray: transportArray})
                .then(res => {
                  if (res.status === 200) {
                    this.$message.success('数据上链成功');
                    const transportInfo = {
                      lng: Number(this.lng),
                      lat: Number(this.lat),
                      cropsId: row.cropsId,
                      status: 1,
                    };
                    this.axios.post("/driver/driver/saveTransport", transportInfo).then(res => {
                      if (res.data.data) {
                        this.load();
                      }
                    })
                  }
                })
                .catch(err => {
                  this.$message.error('存储异常 ' + err);
                });

          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消定位'
            });
          });
    },
    // initAMap(){
    //   const map = new AMap.Map("mapContainer");
    //   AMap.plugin('AMap.Geolocation', function() {
    //     var geolocation = new AMap.Geolocation({
    //       // 是否使用高精度定位，默认：true
    //       enableHighAccuracy: true,
    //       // 设置定位超时时间，默认：无穷大
    //       timeout: 10000,
    //       // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
    //       buttonOffset: new AMap.Pixel(10, 20),
    //       //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
    //       zoomToAccuracy: true,
    //       //  定位按钮的排放位置,  RB表示右下
    //       buttonPosition: 'RB'
    //     });
    //     geolocation.getCurrentPosition();
    //     AMap.event.addListener(geolocation, 'complete', onComplete);
    //     AMap.event.addListener(geolocation, 'error', onError);
    //     function onComplete(data) {
    //       this.cityDetail = data.addressComponent.province + data.addressComponent.city + data.addressComponent.district + data.addressComponent.township;
    //       this.lng = data.position.lng;
    //       this.lat = data.position.lat;
    //       const str = [];
    //       str.push(data.position.lng);
    //       str.push(data.position.lat);
    //
    //     }
    //     function onError(data) {
    //       console.log('定位错误   ' + JSON.stringify(data));
    //     }
    //   })
    // }
    initMap(){
      AMapLoader.load({
        key:"f45cbb1c21e363fa3a60a975788d89ff",             // 申请好的Web端开发者Key，首次调用 load 时必填
        version:"1.4.15",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins:['AMap.Geolocation',
          'AMap.Marker',
          'AMap.Polyline',
          'AMap.MoveAnimation',],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap)=>{
        this.map = new AMap.Map("container",{  //设置地图容器id
          viewMode:"3D",    //是否为3D地图模式
          zoom:7,           //初始化地图级别
          center: [116.407082,39.904483]//初始化地图中心点位置
        })
        this.getCurrentLocation()
        const lineArr = [
          [116.407082,39.904483],
          [116.056963,38.694297],
          [116.056963,38.394297],
          [114.866067,38.434499],
          [113.788693,38.067111],
            [112.5489,37.8706]
        ];
        //标记车辆
        this.marker = new AMap.Marker({
          position: [116.407082,39.904483],
          icon: 'https://webapi.amap.com/images/car.png',
          //坐标偏移
          offset: new AMap.Pixel(-26, -13),
          autoRotation: true,
          angle: -90,
          map: this.map
        });
        // 绘制轨迹路线
        this.polyline = new AMap.Polyline({
          map: this.map,
          //这里替换自己的坐标数据
          path: lineArr,
          borderWeight: 2, // 线条宽度，默认为 1
          strokeColor: 'red', // 线条颜色
          lineJoin: 'round' // 折线拐点连接处样式
        });
        this.map.add(this.polyline);

        //调用方法开启动画
        this.marker.moveAlong(lineArr, 100000);
      }).catch(e=>{
        console.log(e);
      })
    },
    //获取当前定位
    getCurrentLocation(){
      const that = this;
      this.geolocation = new AMap.Geolocation({
        // 是否使用高精度定位，默认：true
        enableHighAccuracy: true,
        // 设置定位超时时间，默认：无穷大
        timeout: 10000,
        // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
        buttonOffset: new AMap.Pixel(10, 20),
        //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        zoomToAccuracy: true,
        //  定位按钮的排放位置,  RB表示右下
        buttonPosition: 'RB'
      });
      this.geolocation.getCurrentPosition(function(status,result){
        if(status=='complete'){
          that.onComplete(result)
        }else{
          that.onError(result)
        }
      })
    },
    onComplete(data) {
      console.log(data)
      this.lng = data.position.lng;
      this.lat = data.position.lat;
      // const str = [];
      // str.push(data.position.lng);
      // str.push(data.position.lat);
      console.log("经纬度"+this.lng+"-"+this.lat)
      const url = `https://restapi.amap.com/v3/geocode/regeo?location=${this.lng},${this.lat}&key=f45cbb1c21e363fa3a60a975788d89ff`;
      Api.get(url)
          .then(response => {
            const { status, regeocode } = response.data;
            console.log(response)
            if (status === '1' && regeocode) {
              this.cityDetail = regeocode.formatted_address;
            } else {
              this.cityDetail = '无法获取地址';
            }
            console.log(this.cityDetail)
          })
          .catch(error => {
            console.error(error);
            this.address = '逆地理编码失败';
          });
    },
    onError(data) {
      console.log('定位错误   ' + JSON.stringify(data));
    }
  },
  mounted() {
    this.initMap()
    // this.initAMap()
    // this.$nextTick(()=>this.initAMap())
  }
}
</script>

<style scoped>
#container{
  padding:0px;
  margin: 0px;
  width: 100%;
  height: 800px;
}
</style>